#!/usr/bin/bash

#============================================
# 检测MySQL服务、主从复制状态是否正常
# 参考：https://www.imooc.com/video/10518
#============================================

# ??? 待验证
clear
#初始化终端颜色，即清除颜色
resetTerminal=$(tput sgr0)
GREEN='\e[1;32m' #绿
RED='\e[1;31m'  #红

function checkMysqlServer() {
    #扫描mysql端口
    nc -z -w2 ${mysqlSlaveServer} 3306 &>/dev/null
    if [ $? -eq 0 ]; then
        echo -e "${GREEN}连接MySQL服务成功!${resetTerminal}"
        mysql -u${mysqlUser} -p${mysqlPwd} -h${mysqlSlaveServer} -e "show slave status\G" | grep "Slave_IO_Running" | awk '{if($2 != "Yes") {print "Slave thread not running! ";exit 1}}'
        if [ $? -eq 0 ]; then #成功后 返回主从复制延迟数
            mysql -u${mysqlUser} -p${mysqlPwd} -h${mysqlSlaveServer} -e "show slave status\G" | grep "Seconds_Behind_Master"
        fi
      else
        echo -e "${RED}连接MySQL服务失败!${resetTerminal}"
    fi
}

checkMysqlServer
